<template>
  <div class="activation-code-generate-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>生成激活码</span>
          <el-button @click="goBack">返回列表</el-button>
        </div>
      </template>

      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
        v-loading="loading"
        class="generate-form"
      >
        <el-form-item label="生成数量" prop="count">
          <el-input-number
            v-model="form.count"
            :min="1"
            :max="100"
            controls-position="right"
          />
          <span class="tip-text">一次最多生成100个</span>
        </el-form-item>

        <el-form-item label="有效天数" prop="days">
          <el-input-number
            v-model="form.days"
            :min="1"
            :max="3650"
            controls-position="right"
          />
          <span class="tip-text">激活后的有效天数</span>
        </el-form-item>

        <el-form-item label="使用次数" prop="usage_count">
          <el-input-number
            v-model="form.usage_count"
            :min="1"
            :max="9999"
            controls-position="right"
          />
          <span class="tip-text">激活码可使用的次数</span>
        </el-form-item>

        <!-- <el-form-item label="所属套餐" prop="plan_id">
          <el-select v-model="form.plan_id" placeholder="请选择套餐">
            <el-option 
              v-for="item in planOptions" 
              :key="item.id" 
              :label="item.name" 
              :value="item.id"
            />
          </el-select>
        </el-form-item> -->

        <el-form-item label="绑定代理" prop="agent_id">
          <el-select
            v-model="form.agent_id"
            placeholder="请选择代理"
            filterable
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="item in agentOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
          <span class="tip-text">选择激活码归属的代理（可选）</span>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm" :loading="generating"
            >生成激活码</el-button
          >
          <el-button @click="goBack">取消</el-button>
        </el-form-item>
      </el-form>

      <!-- 生成结果 -->
      <div v-if="generatedCodes.length" class="result-container">
        <div class="result-header">
          <h3>生成结果 (共 {{ generatedCodes.length }} 个激活码)</h3>
          <div class="action-buttons">
            <el-button size="small" type="primary" @click="copyAllCodes"
              >复制全部</el-button
            >
            <el-button size="small" type="success" @click="exportCodes"
              >导出Excel</el-button
            >
            <el-button size="small" type="info" @click="markAllCodes"
              >标记全部为已处理</el-button
            >
          </div>
        </div>

        <el-table :data="generatedCodes" border stripe>
          <el-table-column type="index" label="#" width="60" />
          <el-table-column prop="code" label="激活码" min-width="200">
            <template #default="scope">
              <div class="code-cell">
                <span>{{ scope.row.code }}</span>
                <el-button
                  size="small"
                  type="primary"
                  link
                  @click="copyCode(scope.row.code)"
                >
                  复制
                </el-button>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="days" label="有效天数" width="100" />
          <el-table-column prop="usage_count" label="使用次数" width="100" />
          <el-table-column prop="created_at" label="生成时间" width="180" />
          <el-table-column label="操作" width="120" fixed="right">
            <template #default="scope">
              <el-button
                size="small"
                type="primary"
                link
                @click="copyCode(scope.row.code)"
              >
                复制
              </el-button>
              <el-button
                size="small"
                type="success"
                link
                @click="exportSingleCode(scope.row)"
              >
                导出
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeMount } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { generateActivationCode } from "@/api/activation-codes";
import { getAgentList } from "@/api/agents";
import { getPlanList } from "@/api/plans";
import { useUserStore } from "@/store/user";

const router = useRouter();
const userStore = useUserStore();
const formRef = ref(null);
const loading = ref(false);
const generating = ref(false);
const generatedCodes = ref([]);

// 检查权限，如果没有权限则返回列表页
onBeforeMount(() => {
  if (userStore.isTest) {
    ElMessage.warning("测试账号不能生成激活码");
    router.push("/activation-code/list");
    return;
  }
});

// 套餐选项
const planOptions = ref([]);
// 代理选项
const agentOptions = ref([]);

// 表单数据
const form = reactive({
  count: 10,
  days: 365,
  usage_count: 10, // 默认使用次数为10
  plan_id: "",
  agent_id: "",
  remark: "",
});

// 表单验证规则
const rules = reactive({
  count: [{ required: true, message: "请输入生成数量", trigger: "blur" }],
  days: [{ required: true, message: "请输入有效天数", trigger: "blur" }],
  usage_count: [{ required: true, message: "请输入使用次数", trigger: "blur" }],
});

// 返回列表页
const goBack = () => {
  router.push("/activation-code/list");
};

// 获取套餐列表
const getPlanOptions = async () => {
  try {
    const res = await getPlanList({ limit: 100 });
    if (res.code === 0) {
      planOptions.value = res.data.list;
      // 如果有套餐，默认选中第一个
      if (planOptions.value.length > 0) {
        form.plan_id = planOptions.value[0].id;
      }
    }
  } catch (error) {
    console.error("获取套餐列表失败", error);
  }
};

// 获取代理列表
const getAgentOptions = async () => {
  try {
    const res = await getAgentList();
    if (res.code === 0) {
      agentOptions.value = res.data.items;
    }
  } catch (error) {
    console.error("获取代理列表失败", error);
  }
};

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return;

  // 再次验证权限
  if (userStore.isTest && !userStore.hasPermission("add:activation_code")) {
    ElMessage.warning("测试账号不能生成激活码");
    return;
  }

  await formRef.value.validate(async (valid) => {
    if (!valid) return;

    generating.value = true;
    try {
      const res = await generateActivationCode({
        count: form.count,
        days: form.days,
        usage_count: form.usage_count, // 明确传递使用次数
        plan_id: form.plan_id,
        agent_id: form.agent_id,
        remark: form.remark,
      });

      if (res.code === 0) {
        ElMessage.success("生成成功");
        generatedCodes.value = res.data;
      } else {
        ElMessage.error(res.message || "生成失败");
      }
    } catch (error) {
      console.error("生成失败", error);
      ElMessage.error("生成失败");
    } finally {
      generating.value = false;
    }
  });
};

// 复制单个激活码
const copyCode = (code) => {
  navigator.clipboard
    .writeText(code)
    .then(() => {
      ElMessage.success("复制成功");
    })
    .catch(() => {
      ElMessage.error("复制失败");
    });
};

// 复制所有激活码
const copyAllCodes = () => {
  const codes = generatedCodes.value.map((item) => item.code).join("\n");
  navigator.clipboard
    .writeText(codes)
    .then(() => {
      ElMessage.success(`成功复制${generatedCodes.value.length}个激活码`);
    })
    .catch(() => {
      ElMessage.error("复制失败");
    });
};

// 导出单个激活码
const exportSingleCode = (code) => {
  exportCodeToCSV([code]);
};

// 导出所有激活码
const exportCodes = () => {
  exportCodeToCSV(generatedCodes.value);
};

// 导出激活码为CSV
const exportCodeToCSV = (codes) => {
  if (!codes || codes.length === 0) return;

  let csvContent = "激活码,有效天数,使用次数,生成时间,备注\n";
  codes.forEach((item) => {
    csvContent += `${item.code},${item.days},${item.usage_count || 0},${
      item.created_at || ""
    },${item.remark || ""}\n`;
  });

  const blob = new Blob([csvContent], { type: "text/csv;charset=utf-8;" });
  const link = document.createElement("a");
  const url = URL.createObjectURL(blob);

  link.setAttribute("href", url);
  link.setAttribute("download", `激活码_${new Date().getTime()}.csv`);
  link.style.visibility = "hidden";

  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);

  ElMessage.success(`成功导出${codes.length}个激活码`);
};

// 标记所有生成的激活码为已处理（已复制和已导出）
const markAllCodes = () => {
  ElMessage.success(`已标记${generatedCodes.value.length}个激活码为已处理`);
  // 此功能实际上需要调用后端API，此处只做前端提示
  // TODO: 实现实际的标记功能
};

onMounted(() => {
  // getPlanOptions()
  getAgentOptions();
});
</script>

<style scoped>
.activation-code-generate-container {
  padding: 20px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.tip-text {
  margin-left: 10px;
  color: #666;
  font-size: 13px;
}
.result-container {
  margin-top: 30px;
  border-top: 1px solid #ebeef5;
  padding-top: 20px;
}
.result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 10px;
}
.result-header h3 {
  margin: 0;
  color: #333;
  font-size: 16px;
  font-weight: 600;
}
.action-buttons {
  display: flex;
  gap: 10px;
}
.generate-form {
  max-width: 700px;
}
.code-cell {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
